package cn.net.xinyi.xs.util;

import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.springframework.context.i18n.LocaleContextHolder;

import cn.net.xinyi.xs.Constants;

public class PageUtil {
	public static int getMainPageSize() {
		Locale locale = LocaleContextHolder.getLocale();
		String pageSize;
		try {
			pageSize = ResourceBundle.getBundle(Constants.BUNDLE_PAGE_KEY,
					locale).getString("main.page.size");
		} catch (MissingResourceException mse) {
			pageSize = "20";
		}
		return Integer.parseInt(pageSize);
	}

	public static int getQueryPageSize() {
		Locale locale = LocaleContextHolder.getLocale();
		String pageSize;
		try {
			pageSize = ResourceBundle.getBundle(Constants.BUNDLE_PAGE_KEY,
					locale).getString("query.page.size");
		} catch (MissingResourceException mse) {
			pageSize = "10";
		}
		return Integer.parseInt(pageSize);
	}

	@SuppressWarnings("unchecked")
	public static String getSortCriterion(Map parameterMap) {
		String sortCriterion = "id";
		Object sort = parameterMap.get("sort");
		if (sort != null) {
			if (sort instanceof String[]) {
				if (!"".equals(((String[]) sort)[0])) {
					sortCriterion = ((String[]) sort)[0];
				}
			} else {
				sortCriterion = (String) sort;
			}
		}
		return sortCriterion;
	}

	@SuppressWarnings("unchecked")
	public static String getSortDirection(Map parameterMap) {
		String sortDirection = "desc";
		Object dir = parameterMap.get("dir");
		if (dir != null) {
			if (dir instanceof String[]) {
				sortDirection = ((String[]) dir)[0];
			} else {
				sortDirection = (String) dir;
			}
		}
		return sortDirection;
	}

	@SuppressWarnings("unchecked")
	public static int getStartIndex(Map parameterMap) {
		int startIndex = 0;
		Object start = parameterMap.get("start");
		if (start != null) {
			if (start instanceof String[]) {
				if (!"".equals(((String[]) start)[0])) {
					startIndex = Integer.parseInt(((String[]) start)[0]);
				}
			} else {
				startIndex = Integer.parseInt((String) start);
			}
		}
		return startIndex;
	}

	@SuppressWarnings("unchecked")
	public static int getLimitSize(Map parameterMap) {
		int limitSize = 20;
		Object limit = parameterMap.get("limit");
		if (limit != null) {
			if (limit instanceof String[]) {
				if (!"".equals(((String[]) limit)[0])) {
					limitSize = Integer.parseInt(((String[]) limit)[0]);
				}
			} else {
				limitSize = Integer.parseInt((String) limit);
			}
		}
		return limitSize;
	}

	@SuppressWarnings("unchecked")
	public static String getStringParameterMap(Map parameterMap, String type) {
		String sortDirection = "";
		Object dir = parameterMap.get(type);
		if (dir != null) {
			if (dir instanceof String[]) {
				sortDirection = ((String[]) dir)[0];
			} else {
				sortDirection = (String) dir;
			}
		}
		return sortDirection;
	}
}
